#!/bin/bash

if [ -z "$(env | grep USER=root)" ];then
	echo "You're not the root!"
	exit 1
fi

trap "echo Please waiting..." INT
trap "echo Please waiting..." QUIT
LOCK_FILE="/tmp/njubras-for-linux.lock"

is_only_one()
{
	if [ -e $LOCK_FILE ];then
		return 1
	else
		return 0
	fi
}

call_script()
{
	case "$1" in
		connect	)
			echo -n "Please input your username: "
			read USERNAME
			while [ -z "$USERNAME" ];do
				echo "Your username can't be empty!"
				echo -n "Please input your username: "
				read USERNAME
			done
			
			echo -n "Please input your password: "
			stty -echo
			read PASSWORD
			stty echo
			echo
			while [ -z "$PASSWORD" ];do
				echo "Your password can't be empty!"
				echo -n "Please input your password: "
				stty -echo
				read PASSWORD
				stty echo
				echo
			done

			
			cd ./scripts

			echo "Connecting..."

			sh bras_control.sh start $USERNAME $PASSWORD #$2
			sh bras_control.sh result
			;;
		disconnect)
			cd ./scripts
			sh bras_control.sh stop #$2
			echo "Disconnected."
			;;
		check	)
			cd ./scripts
			sh check_bras_connect.sh #$2
			echo "Checked."
	esac
}

is_only_one

if [ $? -ne 0 ];then
	echo "It seems that njubras-for-linux has been started. If you don't think so, try \"sudo rm -f $LOCK_FILE\""
	exit 1
fi

if [ "$1" = "connect" ];then
	call_script connect $2
elif [ "$1" = "disconnect" ];then
	call_script disconnect $2
elif [ "$1" = "check" ];then
	call_script check $2
else
	#echo -n "Is off-campus? (y/n) :"
	#read IS_OFF_CAMPUS
	
	echo "1)Connect to the NJUBRAS"
	echo "2)Disconnect to the NJUBRAS"
	echo "3)Check the connection to NJUBRAS"
	echo -n "Please input your option: "
	read OPTION

	#if [ "$IS_OFF_CAMPUS" = [yY] ];then
	#	OFF_CAMPUS="off_campus"
	#fi

	case $OPTION in
		1	)
			INTERFACE=ppp$(cat ./config/extra_options | grep unit | grep -o [0-9])
			if [ -n "$(route -n | grep $INTERFACE)" ];then
				echo "Has connected to NJUBRAS!"
				exit 1
			fi
			call_script connect #$OFF_CAMPUS
		;;
		2	)
			INTERFACE=ppp$(cat ./config/extra_options | grep unit | grep -o [0-9])
			if [ -z "$(route -n | grep $INTERFACE)" ];then
				echo "Hasn't connected to NJUBRAS!"
				exit 1
			fi
			call_script disconnect #$OFF_CAMPUS
		;;
		3	)
			call_script check #$OFF_CAMPUS
		;;
		*	)
			echo "Unkown option."
		;;
	esac

fi


exit 0
